package org.telegram.bot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.telegram.bot.domain.BotChatMember;
import org.telegram.bot.emums.BotCommonEnums;
import org.telegram.bot.mapper.BotChatMemberMapper;
import org.telegram.bot.service.IBotChatMemberService;
import org.telegram.telegrambots.meta.api.objects.User;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 群管理员Service业务层处理
 *
 * @author wyx
 * @date 2024-11-20
 */
@Slf4j
@Service
public class BotChatMemberServiceImpl implements IBotChatMemberService
{
    @Resource
    private BotChatMemberMapper botChatMemberMapper;

    /**
     * 查询群管理员
     *
     * @param id 群管理员主键
     * @return 群管理员
     */
    @Override
    public BotChatMember selectBotChatMemberById(Long id)
    {
        return botChatMemberMapper.selectById(id);
    }

    /**
     * 查询群管理员列表
     *
     * @param botChatMember 群管理员
     * @return 群管理员
     */
    @Override
    public List<BotChatMember> selectBotChatMemberList(BotChatMember botChatMember)
    {
        return botChatMemberMapper.selectBotChatMemberList(botChatMember);
    }

    /**
     * 新增群管理员
     *
     * @param botChatMember 群管理员
     * @return 结果
     */
    @Override
    public int insertBotChatMember(BotChatMember botChatMember)
    {
        return botChatMemberMapper.insert(botChatMember);
    }

    /**
     * 修改群管理员
     *
     * @param botChatMember 群管理员
     * @return 结果
     */
    @Override
    public int updateBotChatMember(BotChatMember botChatMember)
    {
        return botChatMemberMapper.updateById(botChatMember);
    }

    /**
     * 批量删除群管理员
     *
     * @param ids 需要删除的群管理员主键
     * @return 结果
     */
    @Override
    public int deleteBotChatMemberByIds(Long[] ids)
    {
        return botChatMemberMapper.deleteByIds(Arrays.asList(ids));
    }

    /**
     * 删除群管理员信息
     *
     * @param id 群管理员主键
     * @return 结果
     */
    @Override
    public int deleteBotChatMemberById(Long id)
    {
        return botChatMemberMapper.deleteById(id);
    }
    
    /**
     * 删除群管理员信息
     *
     * @param chatId 群主键
     * @return 结果
     */
    @Override
    public int deleteBotChatMemberByChatId(Long chatId)
    {
        return botChatMemberMapper.delete(new LambdaQueryWrapper<BotChatMember>().eq(BotChatMember::getChatId,chatId));
    }
    
    /**
     * 保存和更新
     *
     * @param list
     * @param chatId
     */
    @Override
    public void chatSaveAndUpdate(List<BotChatMember> list,Long chatId){
        List<Long> collect = list.stream().map(BotChatMember::getUserId).toList();
        List<BotChatMember> botChatMembers = botChatMemberMapper.selectList(new LambdaQueryWrapper<BotChatMember>().eq(BotChatMember::getChatId, chatId));
        //botChatMember按照userId转成map
        Map<Long, BotChatMember> map = botChatMembers.stream().collect(Collectors.toMap(BotChatMember::getUserId, item -> item));
        //遍历list，找到在map中的id，更新时间戳，不在的插入数据
        list.forEach(botChatMember -> {
            botChatMember.setChatId(chatId);
            if (map.containsKey(botChatMember.getUserId())){
                botChatMember.setId(map.get(botChatMember.getUserId()).getId());
                botChatMember.setUpdateTime(DateUtils.getNowDate());
                updateBotChatMember(botChatMember);
            }else{
                insertBotChatMember(botChatMember);
            }
        });
        //删掉已不再管理列表里面的旧数据
        //遍历map
        map.values().forEach(botChatMember -> {
            if (!collect.contains(botChatMember.getUserId())){
                deleteBotChatMemberById(botChatMember.getId());
            }
        });
    }
    
    /**
     * 验证用户是否为管理员
     *
     * @param chatId
     * @param userId
     * @return
     */
    @Override
    public Boolean isAdminValid(Long chatId, User user){
        //匿名身份默认通过
        if(BotCommonEnums.CHAT_ROLE_GROUP_ANONYMOUS_BOT.equals(user.getUserName())){
            return true;
        }
        Long l = botChatMemberMapper.selectCount(new LambdaQueryWrapper<BotChatMember>().eq(BotChatMember::getChatId, chatId).eq(BotChatMember::getUserId, user.getId()));
        return SqlHelper.retBool(l);
    }
    
    /**
     * 获取用户加入的群
     *
     * @return
     */
    @Override
    public List<Long> getJoinChatList(){
        BotChatMember query = new BotChatMember();
        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            query.setUserId(SecurityUtils.getUserId());
        }
        return botChatMemberMapper.selectBotChatMemberList(query).stream().map(BotChatMember::getChatId).collect(Collectors.toList());
    }
}
